﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace OrBitDataModule.Common
{
    public static class NetworkUtils
    {
        /// <summary>
        /// 获取所有网络适配器
        /// </summary>
        /// <returns></returns>
        public static NetworkInterface[] GetAllNetworkAdapters() => NetworkInterface.GetAllNetworkInterfaces();
        /// <summary>
        /// 根据网络适配器名称获取IPv4地址
        /// </summary>
        /// <param name="adapterName"></param>
        /// <returns></returns>
        public static string GetIPv4Address(string adapterName)
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface adapter in adapters)
            {
                if (adapter.Name == adapterName)
                {
                    foreach (UnicastIPAddressInformation ipInfo in adapter.GetIPProperties().UnicastAddresses)
                    {
                        if (ipInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            return ipInfo.Address.ToString();
                        }
                    }
                }
            }

            return "";
        }

        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIPAddresses()
        {
            return string.Join("|", Dns.GetHostAddresses(Dns.GetHostName())
                      .Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                      .Select(ip => ip.ToString())
                      .ToArray());
        }

        /// <summary>
        /// 获取MAC地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalMACAddress()
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface nic in nics)
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    return nic.GetPhysicalAddress().ToString();
                }
            }
            return null;
        }

        /// <summary>
        /// 获取计算机名称
        /// </summary>
        /// <returns></returns>
        public static string GetComputerName()
        {
            return Dns.GetHostName();
        }
    }
}
